package app.gui.control
{
	import app.util.*;
	import app.util.image.*;
	
	import flash.display.*;
	import flash.events.*;
	import flash.filters.*;
	
	import mx.containers.*;
	import mx.controls.*;
	import mx.events.*;
	
	public class AquaImage extends Canvas
	{
		private var glow:GlowFilter = new GlowFilter(0xffffff, 0.7, 40, 40, 0.8);
		private var img:Image = new Image();
		private var canvas:Canvas = new Canvas();
		private var config:ImageConfig;
		
		public function AquaImage(cfg:ImageConfig)
		{
			this.config = cfg;
			this.label = cfg.file.name;
			this.horizontalScrollPolicy = "auto";
			this.verticalScrollPolicy = "auto";
			this.setStyle("backgroundColor", 0x000000);
			
			this.img.source = this.toBitmap(cfg.images[0]);
			this.img.filters = [glow];
			this.img.mouseEnabled = false;
			this.img.mouseFocusEnabled = false;
			//this.img.maintainAspectRatio = true;
			//this.img.scaleContent = true;
			this.img.setStyle("horizontalCenter", 0);
			this.img.setStyle("verticalCenter", 0);		
			this.img.alpha = 1.0;
			this.img.data = cfg;
			
			this.img.addEventListener(ResizeEvent.RESIZE, this.relayoutCanvas);
			Mediator.getApplication().addEventListener(ResizeEvent.RESIZE, this.relayoutCanvas);
				
			this.addChild(this.img);
			this.addChild(this.canvas);				
		}

		public function loadImage(data:BitmapData = null):void
		{
			if(data == null)
			{
				this.img.source = this.toBitmap(this.config.images[this.config.stateIndex - 1]);
			}
			else
			{
				this.img.source = this.toBitmap(data);
			}
		}

		public function getImage():Image
		{
			return this.img;
		}
		
		public function getCanvas():Canvas
		{
			return this.canvas;
		}		

		public function getImageConfig():ImageConfig 
		{
			return this.config;
		}
		
		private function toBitmap(d:BitmapData):Bitmap
		{
			return new Bitmap(d, "auto", true);
		}
		
		private function relayoutCanvas(e:Event):void
		{
			this.callLater(function():void
			{
				canvas.x = img.x;
				canvas.y = img.y;
				canvas.width = img.width;
				canvas.height = img.height;
				Mediator.getImageCutter().redraw();
				Mediator.getImageRepair().redraw();
				Mediator.getLogger().log("Relayout for image canvas : (" + img.x + ", " + 
					img.y + ", " + img.width + ", " + img.height + ")"); 
			});
			
		}
	}
}